package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
public class CommonController {

    @Value("${file.base-url:http://localhost:5678}")
    private String baseUrl;

    @Value("${file.upload-dir:D:/share/images/}")
    private String uploadDir;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        log.info("上传文件: {}", file.getOriginalFilename());

        // 验证文件
        if (file.isEmpty()) {
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || (!contentType.equals("image/jpeg") && !contentType.equals("image/png"))) {
            return Result.error("只支持JPG/PNG图片");
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID() + suffix;

        // 创建目录（如果不存在）
        File directory = new File(uploadDir);
        if (!directory.exists()) {
            boolean created = directory.mkdirs();
            log.info("创建目录: {}, 成功: {}", directory.getAbsolutePath(), created);
        }

        // 保存文件
        File dest = new File(directory, fileName);
        file.transferTo(dest);

        log.info("文件保存成功: {}", dest.getAbsolutePath());

        // 返回完整的HTTP URL
        String fileUrl = baseUrl + "/images/" + fileName;
        return Result.success(fileUrl);
    }
}

